package com.vench.teddy.service.impl;

import cn.hutool.core.collection.ListUtil;
import com.vench.teddy.pojo.entity.UserPO;
import com.vench.teddy.repository.UserRepository;
import com.vench.teddy.service.IThreadPoolUserService;
import com.vench.teddy.service.IUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @Author:vench
 * @Date:2024-09-28 18:44
 */
@Service
@AllArgsConstructor
@Slf4j
public class UserServiceImpl implements IUserService {

    private final UserRepository repository;

    private final IThreadPoolUserService threadPoolUserService;

    @Override
    public void batchSaveDemos() {
        log.info("插入开始");

        List<UserPO> list = new ArrayList<>();
        for(int i=0;i<1000000;i++){
            UserPO user = new UserPO();
            user.setName("张飞-"+i);
            user.setGender("男");
            user.setAge(20);
            list.add(user);
        }

        long begin = System.currentTimeMillis();
        repository.saveAll(list);
        long end = System.currentTimeMillis();
        log.info("耗时：" + (end-begin));
    }

    @Override
    public void batchSaveByThreadPool() {
        log.info("使用线程池插入开始");

        List<UserPO> list = new ArrayList<>();
        for(int i=0;i<1000000;i++){
            UserPO user = new UserPO();
            user.setName("张飞-"+i);
            user.setGender("男");
            user.setAge(20);
            list.add(user);
        }

        List<List<UserPO>> lists = ListUtil.partition(list, 100);

        CountDownLatch countDownLatch = new CountDownLatch(lists.size());
        long begin = System.currentTimeMillis();
        for(List<UserPO> userPOList:lists){
            threadPoolUserService.saveAll(userPOList,countDownLatch);
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        long end = System.currentTimeMillis();
        log.info("耗时：" + (end-begin));
    }


}
